﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.Tray.Dto;
using Furion.Logging;

namespace Admin.NET.Application.Service.Tray;
/// <summary>
/// 母托盘服务
/// </summary>
[ApiDescriptionSettings(groups: ApplicationConst.GroupName, Order = 13)]
public class TrayService : IDynamicApiController, ITransient
{


    private readonly IDynamicApiController _dynamicApiController;
    private readonly SqlSugarRepository<TrayEntity> _trayEntity;
    private readonly UserManager _userinfo;


    public TrayService(SqlSugarRepository<TrayEntity> trayEntity, UserManager userinfo)
    {
        _userinfo = userinfo;
        _trayEntity = trayEntity;

    }

    /// <summary>
    /// 获取母托盘 🔖
    /// </summary>
    /// <param name="Trayinput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetTrayPageList"), HttpPost]

    public async Task<SqlSugarPagedList<TrayEntity>> GetTrayPageList(TrayDto Trayinput)
    {

        var list = await _trayEntity.AsQueryable()
         .WhereIF(!string.IsNullOrWhiteSpace(Trayinput.Name), u => u.Name.Contains(Trayinput.Name.Trim()))
         .WhereIF(!string.IsNullOrWhiteSpace(Trayinput.Encoding), u => u.Encoding == Trayinput.Encoding.Trim())
            .OrderBy(u => u.CreateTime, OrderByType.Desc)
            .ToPagedListAsync(Trayinput.Page, Trayinput.PageSize);

        //.WhereIF(!string.IsNullOrWhiteSpace(Trayinput.Search.), u => u.Description.Contains(Trayinput.Description.Trim()))


        return list;
    }

    /// <summary>
    /// 添加母托盘
    /// </summary>
    /// <param name="TrayDto"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "InsertTray"), HttpPost]

    public async Task<long> InsertTray(AddTrayInput TrayDto)
    {
        #region 唯一索引
        Expression<Func<TrayEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(TrayDto.Id);
        #endregion
        var data = await _trayEntity.GetFirstAsync(whereExpression);
        if (data != null)
        {
            throw Oops.Oh(10001, "该记录已存在");
        }

        var entity = TrayDto.Adapt<TrayEntity>();
        if (Enum.IsDefined(entity.Type))
        {
            throw Oops.Oh("托盘类型不合法");
        }
        await _trayEntity.AsInsertable(entity).ExecuteCommandAsync();
        return entity.Id;

    }

    /// <summary>
    /// 修改母托盘
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UpdateTray"), HttpPost]
    public async Task UpdateTray(UpdateTrayDtoInput entity)
    {

        #region 唯一索引
        Expression<Func<TrayEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(entity.Id);
        #endregion
        var Tray = await _trayEntity.GetFirstAsync(whereExpression);

        try
        {
            if (Tray != null)
            {
                if (entity.Isenable == StatusEnum.Disable)
                {
                    throw Oops.Oh("当前母托盘状态停用");
                }
                else
                {
                    //对入参进行赋值
                    entity.UpdateUserId = _userinfo.UserId;
                    entity.UpdateTime = DateTime.Now;
                    entity.UpdateUserName = _userinfo.RealName;
                    entity.Name = entity.Name;
                    entity.Type = entity.Type;
                }
            }
            else
            {
                Log.Information("UpdateTray失败无记录", ErrorCodeEnum.D1002);
                throw Oops.Oh(ErrorCodeEnum.D1002);
            }
        }
        catch (Exception error)
        {
            Log.Information("UpdateTray失败", error.StackTrace);
            throw Oops.Oh("修改母托盘出现错误：" + error.Message + "");
        }
        //api已转为entity
        var updateEntity = entity.Adapt<TrayEntity>();
        await _trayEntity.AsUpdateable(updateEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

    }

    /// <summary>
    /// 删除母托盘🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeleteTray"), HttpPost]
    [DisplayName("删除订单")]
    public async Task DeleteTray(DeleteTrayDtoInput input)
    {
        //var regionTreeList = await _sysRegionRep.AsQueryable().ToChildListAsync(u => u.Pid, input.Id, true);
        //var regionIdList = regionTreeList.Select(u => u.Id).ToList();
        //await _sysRegionRep.DeleteAsync(u => regionIdList.Contains(u.Id));

        #region 唯一索引
        Expression<Func<TrayEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion
        var entity = await _trayEntity.GetFirstAsync(whereExpression) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        if (entity.Isenable != StatusEnum.Enable)
        {
            throw Oops.Oh("母托盘在使用中，正在使用对应的条码,,,这里缺少托盘运行status");
        }
        else
        {
            await _trayEntity.DeleteAsync(entity); // 假删除
            //await _rep.DeleteAsync(entity); // 真删除
        }
    }
}
